#include "MainWindow.h"
#include "ChannelConfigDialog.h"
#include "ChannelCardWidget.h"
#include "DashboardDataWidget.h"
#include "MessageLogPanel.h"
#include "LogViewerWidget.h"
#include "AlarmWidget.h"
#include <QMenuBar>
#include <QToolBar>
#include <QStatusBar>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMessageBox>
#include <QFileDialog>
#include <QCloseEvent>
#include <QApplication>
#include <QPushButton>
#include <QJsonArray>
#include <QDebug>
#include <QThread>
#include <QCoreApplication>
#include <QSettings>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QEvent>
#include <QPixmap>
#include <QPainter>
#include <QMouseEvent>
#include <QStandardPaths>
#include <QSplitter>
#include <QScrollArea>

namespace ModbusPlexLink {

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_channelManager(new ChannelManager(this))
    , m_alarmManager(new AlarmManager(m_channelManager, this))
    , m_mainSplitter(nullptr)           // 新增
    , m_rightSplitter(nullptr)          // 新增
    , m_channelScrollArea(nullptr)      // 新增
    , m_channelListWidget(nullptr)      // 新增
    , m_channelListLayout(nullptr)      // 新增
    , m_dashboardWidget(nullptr)        // 新增
    , m_messageLogPanel(nullptr)        // 新增
    , m_currentChannel(nullptr)         // 新增
    , m_channelTable(nullptr)
    , m_updateTimer(new QTimer(this))
    , m_statusLabel(nullptr)
    , m_channelCountLabel(nullptr)
    , m_runningCountLabel(nullptr)
    , m_alarmIndicator(nullptr)
    , m_configModified(false)
    , m_trayIcon(nullptr)
    , m_trayMenu(nullptr)
    , m_showHideAction(nullptr)
    , m_trayExitAction(nullptr)
    , m_autoStartChannels(false)
    , m_logViewer(nullptr)
    , m_alarmWidget(nullptr)
{
    setWindowTitle("Modbus PlexLink - 数据采集与虚拟化服务系统");
    resize(1400, 800);
    setMinimumSize(1000, 600);
    
    // 设置应用图标
    QIcon appIcon("icon.png");
    if (!appIcon.isNull()) {
        setWindowIcon(appIcon);
        qInfo() << "Application icon loaded from icon.png";
    } else {
        qWarning() << "Failed to load icon.png, using default icon";
    }
    
    setupUi();
    createSystemTray();

    // 初始化工具窗口与日志处理
    m_logViewer = new LogViewerWidget();
    m_logViewer->setWindowIcon(windowIcon());
    m_logViewer->hide();
    LogViewerWidget::installMessageHandler();
    
    // 连接通道管理器信号
    connect(m_channelManager, &ChannelManager::channelCreated,
            this, &MainWindow::onChannelCreated);
    connect(m_channelManager, &ChannelManager::channelDeleted,
            this, &MainWindow::onChannelDeleted);
    connect(m_channelManager, &ChannelManager::channelStateChanged,
            this, &MainWindow::onChannelStateChanged);
    connect(m_channelManager, &ChannelManager::globalError,
            this, [this](const QString& error) {
                statusBar()->showMessage(tr("错误: %1").arg(error), 10000);
                QMessageBox::warning(this, tr("通道错误"), error);
            });

    if (m_alarmManager) {
        connect(m_alarmManager, &AlarmManager::alarmTriggered,
                this, &MainWindow::onAlarmTriggered, Qt::QueuedConnection);
        connect(m_alarmManager, &AlarmManager::alarmAcknowledged,
                this, [this](const QString&) { updateAlarmIndicator(); }, Qt::QueuedConnection);
        connect(m_alarmManager, &AlarmManager::alarmCleared,
                this, [this](const QString&) { updateAlarmIndicator(); }, Qt::QueuedConnection);
    }
    
    // 定时更新界面
    connect(m_updateTimer, &QTimer::timeout, this, &MainWindow::updateChannelTable);
    connect(m_updateTimer, &QTimer::timeout, this, &MainWindow::updateStatusBar);
    m_updateTimer->start(1000);  // 每秒更新
    
    // 加载设置
    QSettings settings("ModbusPlexLink", "MainWindow");
    m_autoStartChannels = settings.value("autoStartChannels", false).toBool();
    
    // 尝试加载默认配置
    QString defaultConfig = "config.json";
    if (QFile::exists(defaultConfig)) {
        if (m_channelManager->loadConfig(defaultConfig)) {
            m_currentConfigFile = defaultConfig;
            m_configModified = false;
            statusBar()->showMessage(tr("已加载配置: %1").arg(defaultConfig), 5000);
        }
    }

    // 加载报警配置
    QString alarmConfig = "alarm_config.json";
    if (QFile::exists(alarmConfig) && m_alarmManager) {
        if (m_alarmManager->loadConfig(alarmConfig)) {
            qInfo() << "Alarm configuration loaded from" << alarmConfig;
        } else {
            qWarning() << "Failed to load alarm configuration from" << alarmConfig;
        }
    }
    
    updateChannelTable();
    updateActions();
    updateAlarmIndicator();
    
    // 如果设置了自动启动，延迟启动所有通道
    if (m_autoStartChannels) {
        QTimer::singleShot(1000, this, &MainWindow::autoStartAllChannels);
    }
}

MainWindow::~MainWindow() {
    // 自动保存报警配置
    if (m_alarmManager) {
        QString alarmConfig = "alarm_config.json";
        if (m_alarmManager->saveConfig(alarmConfig)) {
            qInfo() << "Alarm configuration saved to" << alarmConfig;
        }
    }

    if (m_alarmWidget) {
        m_alarmWidget->close();
        delete m_alarmWidget;
        m_alarmWidget = nullptr;
    }

    if (m_logViewer) {
        m_logViewer->close();
        delete m_logViewer;
        m_logViewer = nullptr;
    }

    LogViewerWidget::uninstallMessageHandler();
    m_channelManager->stopAll();
}

void MainWindow::setupUi() {
    createActions();
    createMenus();
    createToolBar();
    createCentralWidget();
    createStatusBar();
}

void MainWindow::createActions() {
    // 文件菜单
    m_newChannelAction = new QAction(tr("新建通道(&N)"), this);
    m_newChannelAction->setShortcut(QKeySequence::New);
    m_newChannelAction->setStatusTip(tr("创建新的采集转发通道"));
    connect(m_newChannelAction, &QAction::triggered, this, &MainWindow::onNewChannel);
    
    m_loadConfigAction = new QAction(tr("打开配置(&O)..."), this);
    m_loadConfigAction->setShortcut(QKeySequence::Open);
    m_loadConfigAction->setStatusTip(tr("从文件加载配置"));
    connect(m_loadConfigAction, &QAction::triggered, this, &MainWindow::onLoadConfig);
    
    m_saveConfigAction = new QAction(tr("保存配置(&S)"), this);
    m_saveConfigAction->setShortcut(QKeySequence::Save);
    m_saveConfigAction->setStatusTip(tr("保存当前配置"));
    connect(m_saveConfigAction, &QAction::triggered, this, &MainWindow::onSaveConfig);
    
    m_saveConfigAsAction = new QAction(tr("另存为(&A)..."), this);
    m_saveConfigAsAction->setShortcut(QKeySequence::SaveAs);
    m_saveConfigAsAction->setStatusTip(tr("保存配置到新文件"));
    connect(m_saveConfigAsAction, &QAction::triggered, this, &MainWindow::onSaveConfigAs);
    
    m_exitAction = new QAction(tr("退出(&X)"), this);
    m_exitAction->setShortcut(QKeySequence::Quit);
    m_exitAction->setStatusTip(tr("退出应用程序"));
    connect(m_exitAction, &QAction::triggered, this, &MainWindow::onExit);
    
    // 通道操作
    m_editChannelAction = new QAction(tr("编辑通道(&E)"), this);
    m_editChannelAction->setStatusTip(tr("编辑选中的通道配置"));
    connect(m_editChannelAction, &QAction::triggered, this, &MainWindow::onEditChannel);
    
    m_deleteChannelAction = new QAction(tr("删除通道(&D)"), this);
    m_deleteChannelAction->setStatusTip(tr("删除选中的通道"));
    connect(m_deleteChannelAction, &QAction::triggered, this, &MainWindow::onDeleteChannel);
    
    m_startChannelAction = new QAction(tr("启动通道(&T)"), this);
    m_startChannelAction->setStatusTip(tr("启动选中的通道"));
    connect(m_startChannelAction, &QAction::triggered, this, &MainWindow::onStartChannel);
    
    m_stopChannelAction = new QAction(tr("停止通道(&P)"), this);
    m_stopChannelAction->setStatusTip(tr("停止选中的通道"));
    connect(m_stopChannelAction, &QAction::triggered, this, &MainWindow::onStopChannel);
    
    m_startAllAction = new QAction(tr("启动全部(&L)"), this);
    m_startAllAction->setStatusTip(tr("启动所有通道"));
    connect(m_startAllAction, &QAction::triggered, this, &MainWindow::onStartAllChannels);
    
    m_stopAllAction = new QAction(tr("停止全部(&H)"), this);
    m_stopAllAction->setStatusTip(tr("停止所有通道"));
    connect(m_stopAllAction, &QAction::triggered, this, &MainWindow::onStopAllChannels);
    
    // 帮助菜单
    m_aboutAction = new QAction(tr("关于(&A)"), this);
    m_aboutAction->setStatusTip(tr("关于 Modbus PlexLink"));
    connect(m_aboutAction, &QAction::triggered, this, &MainWindow::onAbout);

    // 工具
    m_logViewerAction = new QAction(tr("系统日志(&L)"), this);
    m_logViewerAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L));
    m_logViewerAction->setStatusTip(tr("查看系统运行日志"));
    connect(m_logViewerAction, &QAction::triggered, this, &MainWindow::onShowLogViewer);

    m_alarmManagerAction = new QAction(tr("报警管理(&A)"), this);
    m_alarmManagerAction->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_A));
    m_alarmManagerAction->setStatusTip(tr("打开报警管理窗口"));
    connect(m_alarmManagerAction, &QAction::triggered, this, &MainWindow::onShowAlarmManager);
    
    // 设置菜单 - 自动启动选项
    QAction* autoStartAction = new QAction(tr("启动时自动运行所有通道(&R)"), this);
    autoStartAction->setCheckable(true);
    autoStartAction->setChecked(m_autoStartChannels);
    connect(autoStartAction, &QAction::triggered, this, [this, autoStartAction]() {
        m_autoStartChannels = autoStartAction->isChecked();
        QSettings settings("ModbusPlexLink", "MainWindow");
        settings.setValue("autoStartChannels", m_autoStartChannels);
        statusBar()->showMessage(
            m_autoStartChannels ? 
                tr("已启用：启动时自动运行所有通道") : 
                tr("已禁用：启动时自动运行所有通道"), 
            3000);
    });
    
    // 将设置Action添加到成员变量以供菜单使用
    m_aboutAction->setData(QVariant::fromValue(autoStartAction));
}

void MainWindow::createMenus() {
    QMenuBar* menuBar = this->menuBar();
    
    // 文件菜单
    QMenu* fileMenu = menuBar->addMenu(tr("文件(&F)"));
    fileMenu->addAction(m_newChannelAction);
    fileMenu->addSeparator();
    fileMenu->addAction(m_loadConfigAction);
    fileMenu->addAction(m_saveConfigAction);
    fileMenu->addAction(m_saveConfigAsAction);
    fileMenu->addSeparator();
    fileMenu->addAction(m_exitAction);
    
    // 通道菜单
    QMenu* channelMenu = menuBar->addMenu(tr("通道(&C)"));
    channelMenu->addAction(m_editChannelAction);
    channelMenu->addAction(m_deleteChannelAction);
    channelMenu->addSeparator();
    channelMenu->addAction(m_startChannelAction);
    channelMenu->addAction(m_stopChannelAction);
    channelMenu->addSeparator();
    channelMenu->addAction(m_startAllAction);
    channelMenu->addAction(m_stopAllAction);
    
    // 设置菜单
    QMenu* settingsMenu = menuBar->addMenu(tr("设置(&S)"));
    QAction* autoStartAction = qvariant_cast<QAction*>(m_aboutAction->data());
    if (autoStartAction) {
        settingsMenu->addAction(autoStartAction);
    }

    // 工具菜单
    QMenu* toolsMenu = menuBar->addMenu(tr("工具(&T)"));
    toolsMenu->addAction(m_logViewerAction);
    toolsMenu->addAction(m_alarmManagerAction);
    
    // 帮助菜单
    QMenu* helpMenu = menuBar->addMenu(tr("帮助(&H)"));
    helpMenu->addAction(m_aboutAction);
}

void MainWindow::createToolBar() {
    QToolBar* toolBar = addToolBar(tr("主工具栏"));
    toolBar->setMovable(false);
    toolBar->setIconSize(QSize(24, 24));
    
    toolBar->addAction(m_newChannelAction);
    toolBar->addAction(m_loadConfigAction);
    toolBar->addAction(m_saveConfigAction);
    toolBar->addSeparator();
    toolBar->addAction(m_editChannelAction);
    toolBar->addAction(m_deleteChannelAction);
    toolBar->addSeparator();
    toolBar->addAction(m_startChannelAction);
    toolBar->addAction(m_stopChannelAction);
    toolBar->addSeparator();
    toolBar->addAction(m_startAllAction);
    toolBar->addAction(m_stopAllAction);
    toolBar->addSeparator();
    toolBar->addAction(m_logViewerAction);
    toolBar->addAction(m_alarmManagerAction);
}

void MainWindow::createCentralWidget() {
    // 创建主分割器（水平分割：左侧通道列表 | 右侧数据+日志）
    m_mainSplitter = new QSplitter(Qt::Horizontal, this);
    m_mainSplitter->setObjectName("mainSplitter");
    m_mainSplitter->setChildrenCollapsible(false);

    // ============ 左侧：通道卡片列表 ============
    QWidget* leftPanel = new QWidget(this);
    leftPanel->setObjectName("leftPanel");
    QVBoxLayout* leftLayout = new QVBoxLayout(leftPanel);
    leftLayout->setContentsMargins(12, 12, 12, 12);
    leftLayout->setSpacing(12);

    // 标题和操作按钮
    QHBoxLayout* headerLayout = new QHBoxLayout();
    QLabel* titleLabel = new QLabel(tr("📋 通道列表"), leftPanel);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(12);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    headerLayout->addWidget(titleLabel);

    headerLayout->addStretch();

    QPushButton* addChannelBtn = new QPushButton("➕", leftPanel);
    addChannelBtn->setObjectName("iconButtonHeader");
    addChannelBtn->setFixedSize(32, 32);
    addChannelBtn->setCursor(Qt::PointingHandCursor);
    addChannelBtn->setToolTip(tr("新建通道"));
    connect(addChannelBtn, &QPushButton::clicked, this, &MainWindow::onNewChannel);
    headerLayout->addWidget(addChannelBtn);

    leftLayout->addLayout(headerLayout);

    // 通道卡片滚动区域
    m_channelScrollArea = new QScrollArea(leftPanel);
    m_channelScrollArea->setWidgetResizable(true);
    m_channelScrollArea->setFrameShape(QFrame::NoFrame);
    m_channelScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_channelScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    m_channelListWidget = new QWidget();
    m_channelListLayout = new QVBoxLayout(m_channelListWidget);
    m_channelListLayout->setContentsMargins(0, 0, 0, 0);
    m_channelListLayout->setSpacing(8);
    m_channelListLayout->setAlignment(Qt::AlignTop);

    m_channelScrollArea->setWidget(m_channelListWidget);
    leftLayout->addWidget(m_channelScrollArea);

    // 左侧面板最小宽度
    leftPanel->setMinimumWidth(280);
    m_mainSplitter->addWidget(leftPanel);

    // ============ 右侧：上下分割（数据仪表盘 | 报文日志） ============
    m_rightSplitter = new QSplitter(Qt::Vertical, this);
    m_rightSplitter->setObjectName("rightSplitter");
    m_rightSplitter->setChildrenCollapsible(false);

    // 右上：仪表盘数据展示
    QWidget* dashboardPanel = new QWidget(this);
    dashboardPanel->setObjectName("dashboardPanel");
    QVBoxLayout* dashboardLayout = new QVBoxLayout(dashboardPanel);
    dashboardLayout->setContentsMargins(12, 12, 12, 12);
    dashboardLayout->setSpacing(8);

    QLabel* dashboardTitle = new QLabel(tr("📊 实时数据"), dashboardPanel);
    dashboardTitle->setObjectName("panelTitle");
    QFont dashboardFont = dashboardTitle->font();
    dashboardFont.setPointSize(11);
    dashboardFont.setBold(true);
    dashboardTitle->setFont(dashboardFont);
    dashboardLayout->addWidget(dashboardTitle);

    m_dashboardWidget = new DashboardDataWidget(dashboardPanel);
    dashboardLayout->addWidget(m_dashboardWidget);

    m_rightSplitter->addWidget(dashboardPanel);

    // 右下：报文与日志面板
    m_messageLogPanel = new MessageLogPanel(this);
    m_rightSplitter->addWidget(m_messageLogPanel);

    // 设置右侧上下分割比例 (60% : 40%)
    m_rightSplitter->setStretchFactor(0, 60);
    m_rightSplitter->setStretchFactor(1, 40);

    m_mainSplitter->addWidget(m_rightSplitter);

    // 设置主分割器左右比例 (30% : 70%)
    m_mainSplitter->setStretchFactor(0, 30);
    m_mainSplitter->setStretchFactor(1, 70);

    setCentralWidget(m_mainSplitter);

    // 应用现代化主题
    applyModernTheme();

    // 初始化通道卡片列表
    updateChannelCards();
}

void MainWindow::createStatusBar() {
    m_statusLabel = new QLabel(tr("就绪"), this);
    m_channelCountLabel = new QLabel(tr("通道: 0"), this);
    m_runningCountLabel = new QLabel(tr("运行: 0"), this);
    m_alarmIndicator = new QLabel(tr("报警: 0"), this);
    m_alarmIndicator->setStyleSheet("padding: 0 10px; font-weight: bold; color: #2e7d32;");
    m_alarmIndicator->setCursor(Qt::PointingHandCursor);
    m_alarmIndicator->installEventFilter(this);
    
    statusBar()->addWidget(m_statusLabel, 1);
    statusBar()->addPermanentWidget(m_channelCountLabel);
    statusBar()->addPermanentWidget(m_runningCountLabel);
    statusBar()->addPermanentWidget(m_alarmIndicator);
}

// 旧的 getSelectedChannelName 已移到文件末尾重新实现（不再依赖表格）
// 见第1597行的新实现

void MainWindow::updateActions() {
    QString selectedChannel = getSelectedChannelName();
    bool hasSelection = !selectedChannel.isEmpty();
    bool hasChannels = m_channelManager->getChannelCount() > 0;
    
    m_editChannelAction->setEnabled(hasSelection);
    m_deleteChannelAction->setEnabled(hasSelection);
    m_startChannelAction->setEnabled(hasSelection);
    m_stopChannelAction->setEnabled(hasSelection);
    
    m_startAllAction->setEnabled(hasChannels);
    m_stopAllAction->setEnabled(hasChannels);
    
    m_saveConfigAction->setEnabled(hasChannels);
    m_saveConfigAsAction->setEnabled(hasChannels);
}

QString MainWindow::channelStateToString(ChannelState state) const {
    switch (state) {
        case ChannelState::Stopped:  return tr("已停止");
        case ChannelState::Starting: return tr("启动中");
        case ChannelState::Running:  return tr("运行中");
        case ChannelState::Stopping: return tr("停止中");
        case ChannelState::Error:    return tr("错误");
        default: return tr("未知");
    }
}

QColor MainWindow::channelStateColor(ChannelState state) const {
    switch (state) {
        case ChannelState::Stopped:  return QColor(150, 150, 150);
        case ChannelState::Starting: return QColor(255, 165, 0);
        case ChannelState::Running:  return QColor(34, 139, 34);
        case ChannelState::Stopping: return QColor(255, 165, 0);
        case ChannelState::Error:    return QColor(220, 20, 60);
        default: return QColor(0, 0, 0);
    }
}

QString MainWindow::getChannelConnectionStatus(Channel* channel) const {
    if (!channel) {
        return tr("N/A");
    }
    
    // 获取采集器连接状态
    QList<ICollector*> collectors = channel->getCollectors();
    int collectorTotal = collectors.size();
    int collectorConnected = 0;
    
    for (ICollector* collector : collectors) {
        if (collector && collector->isConnected()) {
            collectorConnected++;
        }
    }
    
    // 获取服务器连接状态
    QList<IServer*> servers = channel->getServers();
    int serverTotal = servers.size();
    int serverRunning = 0;
    int totalClients = 0;
    
    for (IServer* server : servers) {
        if (server && server->isRunning()) {
            serverRunning++;
            totalClients += server->getClientCount();
        }
    }
    
    // 构建状态字符串
    QString status;
    if (collectorTotal > 0) {
        status += tr("采集器: %1/%2").arg(collectorConnected).arg(collectorTotal);
    }
    
    if (serverTotal > 0) {
        if (!status.isEmpty()) {
            status += " | ";
        }
        status += tr("服务器: %1/%2").arg(serverRunning).arg(serverTotal);
        if (totalClients > 0) {
            status += tr(" (%1客户端)").arg(totalClients);
        }
    }
    
    if (status.isEmpty()) {
        status = tr("无设备");
    }
    
    return status;
}

void MainWindow::updateAlarmIndicator() {
    if (!m_alarmIndicator) {
        return;
    }

    if (!m_alarmManager) {
        m_alarmIndicator->setText(tr("报警: -"));
        m_alarmIndicator->setStyleSheet("padding: 0 10px; font-weight: bold; color: #757575;");
        return;
    }

    int activeAlarms = m_alarmManager->getActiveAlarmCount();
    int criticalAlarms = m_alarmManager->getAlarmCount(AlarmPriority::Critical);

    QString color;
    QString text;
    if (activeAlarms == 0) {
        text = tr("报警: 0 (正常)");
        color = "#2e7d32";
    } else if (criticalAlarms > 0) {
        text = tr("报警: %1 (严重)").arg(activeAlarms);
        color = "#b71c1c";
    } else {
        text = tr("报警: %1").arg(activeAlarms);
        color = "#e67e22";
    }

    m_alarmIndicator->setText(text);
    m_alarmIndicator->setStyleSheet(
        QStringLiteral("padding: 0 10px; font-weight: bold; color: %1;").arg(color));
}

// void MainWindow::updateChannelTable() {
//     QStringList channelNames = m_channelManager->getChannelNames();
    
//     // 保存当前选中
//     QString selectedChannel = getSelectedChannelName();
    
//     m_channelTable->setRowCount(channelNames.size());
    
//     for (int i = 0; i < channelNames.size(); ++i) {
//         QString name = channelNames[i];
//         Channel* channel = m_channelManager->getChannel(name);
//         if (!channel) continue;
        
//         // 通道名称
//         QTableWidgetItem* nameItem = new QTableWidgetItem(name);
//         nameItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
//         m_channelTable->setItem(i, 0, nameItem);
        
//         // 状态
//         ChannelState state = channel->getState();
//         QTableWidgetItem* stateItem = new QTableWidgetItem(channelStateToString(state));
//         stateItem->setTextAlignment(Qt::AlignCenter);
//         stateItem->setForeground(QBrush(channelStateColor(state)));
//         m_channelTable->setItem(i, 1, stateItem);
        
//         // 连接状态（新增）
//         QString connectionStatus = getChannelConnectionStatus(channel);
//         QTableWidgetItem* connItem = new QTableWidgetItem(connectionStatus);
//         connItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
//         connItem->setFont(QFont("Consolas", 8)); // 使用等宽字体
//         m_channelTable->setItem(i, 2, connItem);
        
//         // 采集器数量
//         int collectorCount = channel->getCollectors().size();
//         QTableWidgetItem* collectorItem = new QTableWidgetItem(QString::number(collectorCount));
//         collectorItem->setTextAlignment(Qt::AlignCenter);
//         m_channelTable->setItem(i, 3, collectorItem);
        
//         // 服务器数量
//         int serverCount = channel->getServers().size();
//         QTableWidgetItem* serverItem = new QTableWidgetItem(QString::number(serverCount));
//         serverItem->setTextAlignment(Qt::AlignCenter);
//         m_channelTable->setItem(i, 4, serverItem);
        
//         // 虚拟设备数量（需要从配置中获取）
//         ChannelConfig config = channel->getConfig();
//         int virtualDeviceCount = 0;
//         for (const QJsonObject& server : config.servers) {
//             if (server.contains("virtualDevices")) {
//                 virtualDeviceCount += server["virtualDevices"].toArray().size();
//             }
//         }
//         QTableWidgetItem* vdItem = new QTableWidgetItem(QString::number(virtualDeviceCount));
//         vdItem->setTextAlignment(Qt::AlignCenter);
//         m_channelTable->setItem(i, 5, vdItem);
        
//         // 描述
//         QTableWidgetItem* descItem = new QTableWidgetItem(config.description);
//         descItem->setToolTip(config.description);
//         m_channelTable->setItem(i, 6, descItem);
        
//         // 操作按钮
//         QWidget* btnWidget = new QWidget();
//         QHBoxLayout* btnLayout = new QHBoxLayout(btnWidget);
//         btnLayout->setContentsMargins(2, 2, 2, 2);
//         btnLayout->setSpacing(4);
        
//         QPushButton* startBtn = new QPushButton(tr("启动"));
//         QPushButton* stopBtn = new QPushButton(tr("停止"));
//         startBtn->setMaximumWidth(60);
//         stopBtn->setMaximumWidth(60);
        
//         startBtn->setEnabled(state == ChannelState::Stopped || state == ChannelState::Error);
//         stopBtn->setEnabled(state == ChannelState::Running);
        
//         connect(startBtn, &QPushButton::clicked, [this, name]() {
//             m_channelManager->startChannel(name);
//         });
//         connect(stopBtn, &QPushButton::clicked, [this, name]() {
//             m_channelManager->stopChannel(name);
//         });
        
//         btnLayout->addWidget(startBtn);
//         btnLayout->addWidget(stopBtn);
//         btnLayout->addStretch();
        
//         m_channelTable->setCellWidget(i, 7, btnWidget);
        
//         // 恢复选中
//         if (name == selectedChannel) {
//             m_channelTable->selectRow(i);
//         }
//     }
    
//     updateActions();
// }

void MainWindow::updateStatusBar() {
    int totalChannels = m_channelManager->getChannelCount();
    int runningChannels = 0;
    
    for (const QString& name : m_channelManager->getChannelNames()) {
        Channel* channel = m_channelManager->getChannel(name);
        if (channel && channel->isRunning()) {
            runningChannels++;
        }
    }
    
    m_channelCountLabel->setText(tr("通道: %1").arg(totalChannels));
    m_runningCountLabel->setText(tr("运行: %1").arg(runningChannels));
    updateAlarmIndicator();
}

void MainWindow::onNewChannel() {
    ChannelConfigDialog dialog(nullptr, m_channelManager, this);
    dialog.setWindowTitle(tr("新建通道"));
    
    if (dialog.exec() == QDialog::Accepted) {
        ChannelConfig config = dialog.getConfig();
        Channel* channel = m_channelManager->createChannel(config);
        if (channel) {
            m_configModified = true;
            statusBar()->showMessage(tr("通道 '%1' 已创建").arg(config.name), 3000);
            updateChannelTable();
        } else {
            QMessageBox::warning(this, tr("错误"), 
                tr("创建通道失败：通道名称 '%1' 已存在").arg(config.name));
        }
    }
}

void MainWindow::onLoadConfig() {
    if (!saveConfigIfNeeded()) {
        return;
    }
    
    QString filename = QFileDialog::getOpenFileName(
        this, tr("打开配置文件"), QString(),
        tr("JSON配置文件 (*.json);;所有文件 (*.*)"));
    
    if (!filename.isEmpty()) {
        if (m_channelManager->loadConfig(filename)) {
            m_currentConfigFile = filename;
            m_configModified = false;
            statusBar()->showMessage(tr("配置已加载: %1").arg(filename), 5000);
            updateChannelTable();
        } else {
            QMessageBox::critical(this, tr("错误"), 
                tr("加载配置文件失败: %1").arg(filename));
        }
    }
}

void MainWindow::onSaveConfig() {
    if (m_currentConfigFile.isEmpty()) {
        onSaveConfigAs();
        return;
    }
    
    saveConfigWithChannelRestart(m_currentConfigFile);
}

void MainWindow::onSaveConfigAs() {
    QString filename = QFileDialog::getSaveFileName(
        this, tr("保存配置文件"), "config.json",
        tr("JSON配置文件 (*.json);;所有文件 (*.*)"));
    
    if (!filename.isEmpty()) {
        saveConfigWithChannelRestart(filename);
    }
}

void MainWindow::saveConfigWithChannelRestart(const QString& filename) {
    // 收集所有运行中的通道
    QStringList runningChannels;
    QList<QString> allChannels = m_channelManager->getChannelNames();
    
    for (const QString& name : allChannels) {
        Channel* channel = m_channelManager->getChannel(name);
        if (channel && channel->getState() == ChannelState::Running) {
            runningChannels.append(name);
        }
    }
    
    // 如果有运行中的通道，先停止
    if (!runningChannels.isEmpty()) {
        qInfo() << "Stopping" << runningChannels.size() << "running channels before saving config...";
        statusBar()->showMessage(
            tr("正在停止 %1 个运行中的通道以保存配置...").arg(runningChannels.size()), 3000);
        
        // 停止所有运行中的通道
        for (const QString& name : runningChannels) {
            Channel* channel = m_channelManager->getChannel(name);
            if (channel) {
                channel->stop();
            }
        }
        
        // 等待所有通道停止（最多等待5秒）
        int waitCount = 0;
        bool allStopped = false;
        while (waitCount < 50 && !allStopped) {
            QThread::msleep(100);
            QCoreApplication::processEvents();
            
            allStopped = true;
            for (const QString& name : runningChannels) {
                Channel* channel = m_channelManager->getChannel(name);
                if (channel && channel->getState() != ChannelState::Stopped) {
                    allStopped = false;
                    break;
                }
            }
            waitCount++;
        }
        
        if (!allStopped) {
            QMessageBox::warning(this, tr("警告"), 
                tr("部分通道停止超时，但将继续保存配置"));
        }
        
        updateChannelTable();
        qInfo() << "All channels stopped, proceeding to save config...";
    }
    
    // 保存配置
    bool saveSuccess = m_channelManager->saveConfig(filename);
    
    if (saveSuccess) {
        m_currentConfigFile = filename;
        m_configModified = false;
        statusBar()->showMessage(tr("配置已保存: %1").arg(filename), 3000);
        qInfo() << "Config saved successfully to:" << filename;
    } else {
        QMessageBox::critical(this, tr("错误"), 
            tr("保存配置文件失败: %1").arg(filename));
        
        // 保存失败，但仍然尝试重启通道
        if (!runningChannels.isEmpty()) {
            statusBar()->showMessage(tr("保存失败，正在重启通道..."), 3000);
        }
    }
    
    // 重新启动之前运行的通道
    if (!runningChannels.isEmpty()) {
        qInfo() << "Restarting" << runningChannels.size() << "channels...";
        statusBar()->showMessage(
            tr("正在重新启动 %1 个通道...").arg(runningChannels.size()), 3000);
        
        int successCount = 0;
        for (const QString& name : runningChannels) {
            Channel* channel = m_channelManager->getChannel(name);
            if (channel && channel->start()) {
                successCount++;
            }
        }
        
        updateChannelTable();
        
        if (saveSuccess) {
            if (successCount == runningChannels.size()) {
                statusBar()->showMessage(
                    tr("配置已保存，%1 个通道已重新启动").arg(successCount), 5000);
            } else {
                QMessageBox::warning(this, tr("警告"), 
                    tr("配置已保存，但只有 %1/%2 个通道成功重启")
                        .arg(successCount).arg(runningChannels.size()));
                statusBar()->showMessage(
                    tr("配置已保存，部分通道启动失败 (%1/%2)")
                        .arg(successCount).arg(runningChannels.size()), 5000);
            }
        } else {
            statusBar()->showMessage(
                tr("保存失败，%1/%2 个通道已重启")
                    .arg(successCount).arg(runningChannels.size()), 5000);
        }
        
        qInfo() << "Restart complete:" << successCount << "/" << runningChannels.size() << "channels running";
    }
}

void MainWindow::onExit() {
    close();
}

void MainWindow::onEditChannel() {
    QString channelName = getSelectedChannelName();
    if (channelName.isEmpty()) {
        return;
    }
    
    Channel* channel = m_channelManager->getChannel(channelName);
    if (!channel) {
        return;
    }
    
    // 记录通道原来的运行状态
    bool wasRunning = (channel->getState() == ChannelState::Running);
    
    ChannelConfigDialog dialog(channel, m_channelManager, this);
    dialog.setWindowTitle(tr("编辑通道 - %1").arg(channelName));
    
    if (dialog.exec() == QDialog::Accepted) {
        ChannelConfig config = dialog.getConfig();
        
        // 如果通道正在运行，需要先停止才能配置
        if (wasRunning) {
            qInfo() << "Stopping channel" << channelName << "before applying new configuration...";
            channel->stop();
            
            // 等待通道完全停止（最多等待3秒）
            int waitCount = 0;
            while (channel->getState() != ChannelState::Stopped && waitCount < 30) {
                QThread::msleep(100);
                QCoreApplication::processEvents();
                waitCount++;
            }
            
            if (channel->getState() != ChannelState::Stopped) {
                QMessageBox::warning(this, tr("警告"), 
                    tr("通道 '%1' 停止超时，无法应用新配置").arg(channelName));
                return;
            }
            
            updateChannelTable();
        }
        
        // 应用新配置
        if (channel->configure(config)) {
            m_configModified = true;
            
            // 如果通道原来在运行，重新启动
            if (wasRunning) {
                qInfo() << "Restarting channel" << channelName << "with new configuration...";
                if (channel->start()) {
                    statusBar()->showMessage(
                        tr("通道 '%1' 配置已更新并重新启动").arg(channelName), 3000);
                } else {
                    QMessageBox::warning(this, tr("警告"), 
                        tr("通道 '%1' 配置已更新，但重新启动失败").arg(channelName));
                    statusBar()->showMessage(
                        tr("通道 '%1' 配置已更新（启动失败）").arg(channelName), 5000);
                }
            } else {
                statusBar()->showMessage(tr("通道 '%1' 配置已更新").arg(channelName), 3000);
            }
            
            updateChannelTable();
        } else {
            QMessageBox::warning(this, tr("错误"), tr("更新通道配置失败"));
            
            // 如果配置失败但通道原来在运行，尝试恢复运行状态
            if (wasRunning) {
                channel->start();
                updateChannelTable();
            }
        }
    }
}

void MainWindow::onDeleteChannel() {
    QString channelName = getSelectedChannelName();
    if (channelName.isEmpty()) {
        return;
    }
    
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, tr("确认删除"), 
        tr("确定要删除通道 '%1' 吗？").arg(channelName),
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        if (m_channelManager->deleteChannel(channelName)) {
            m_configModified = true;
            statusBar()->showMessage(tr("通道 '%1' 已删除").arg(channelName), 3000);
            updateChannelTable();
        } else {
            QMessageBox::warning(this, tr("错误"), tr("删除通道失败"));
        }
    }
}

void MainWindow::onStartChannel() {
    QString channelName = getSelectedChannelName();
    if (!channelName.isEmpty()) {
        statusBar()->showMessage(tr("正在后台启动通道 '%1'，请稍候...").arg(channelName), 5000);
        m_channelManager->startChannel(channelName);
    }
}

void MainWindow::onStopChannel() {
    QString channelName = getSelectedChannelName();
    if (!channelName.isEmpty()) {
        m_channelManager->stopChannel(channelName);
    }
}

void MainWindow::onStartAllChannels() {
    int count = m_channelManager->getChannelCount();
    statusBar()->showMessage(tr("正在后台启动 %1 个通道，请稍候...").arg(count), 5000);
    m_channelManager->startAll();
}

void MainWindow::onStopAllChannels() {
    m_channelManager->stopAll();
    statusBar()->showMessage(tr("正在停止所有通道..."), 3000);
}

void MainWindow::onAbout() {
    QMessageBox::about(this, tr("关于 Modbus PlexLink"),
        tr("<h2>Modbus PlexLink</h2>"
           "<p>版本 1.0</p>"
           "<p>数据采集与虚拟化服务系统</p>"
           "<p>支持 Modbus TCP 协议的数据采集、转换和虚拟化</p>"
           "<p>Copyright © 2025</p>"));
}

void MainWindow::onShowLogViewer() {
    if (!m_logViewer) {
        m_logViewer = new LogViewerWidget();
        m_logViewer->setWindowIcon(windowIcon());
        m_logViewer->hide();
    }

    m_logViewer->show();
    m_logViewer->raise();
    m_logViewer->activateWindow();
}

void MainWindow::onShowAlarmManager() {
    if (!m_alarmManager) {
        QMessageBox::warning(this, tr("报警管理"), tr("报警管理器尚未初始化。"));
        return;
    }

    if (!m_alarmWidget) {
        m_alarmWidget = new AlarmWidget(m_alarmManager, m_channelManager);
        m_alarmWidget->setWindowIcon(windowIcon());
    }

    m_alarmWidget->show();
    m_alarmWidget->raise();
    m_alarmWidget->activateWindow();
}

void MainWindow::onAlarmTriggered(const AlarmEvent& event) {
    // 更新报警指示器
    updateAlarmIndicator();

    // 构建通知消息
    QString priorityStr;
    switch (event.priority) {
        case AlarmPriority::Low: priorityStr = tr("低"); break;
        case AlarmPriority::Medium: priorityStr = tr("中"); break;
        case AlarmPriority::High: priorityStr = tr("高"); break;
        case AlarmPriority::Critical: priorityStr = tr("紧急"); break;
    }

    QString title = QString("[%1] %2").arg(priorityStr, event.ruleName);
    QString message = QString("%1\n通道: %2 | 标签: %3\n当前值: %4")
        .arg(event.message)
        .arg(event.channelName)
        .arg(event.tagName)
        .arg(event.value.toString());

    // 系统托盘通知
    if (m_trayIcon && m_trayIcon->isVisible()) {
        QSystemTrayIcon::MessageIcon icon;
        switch (event.priority) {
            case AlarmPriority::Critical:
            case AlarmPriority::High:
                icon = QSystemTrayIcon::Critical;
                break;
            case AlarmPriority::Medium:
                icon = QSystemTrayIcon::Warning;
                break;
            default:
                icon = QSystemTrayIcon::Information;
                break;
        }
        m_trayIcon->showMessage(title, message, icon, 5000);
    }

    // 播放报警音效（仅针对高优先级和紧急报警）
    if (event.priority == AlarmPriority::High || event.priority == AlarmPriority::Critical) {
        // 播放系统默认的警告音
        QApplication::beep();
    }

    // 在状态栏显示报警信息
    statusBar()->showMessage(QString(tr("报警触发: %1")).arg(title), 10000);

    // 记录到日志
    qWarning() << "Alarm triggered:" << title << "-" << message;
}

// 旧的信号处理方法已移到文件末尾重新实现（使用新的卡片架构）
// 见第1538行开始的新实现

// 已弃用：使用卡片列表代替表格
// void MainWindow::onChannelTableSelectionChanged() {
//     updateActions();
// }

// 已弃用：使用卡片点击事件
// void MainWindow::onChannelTableDoubleClicked(int row, int column) {
//     Q_UNUSED(column);
//     if (row >= 0) {
//         onEditChannel();
//     }
// }

bool MainWindow::saveConfigIfNeeded() {
    if (!m_configModified) {
        return true;
    }
    
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, tr("保存配置"),
        tr("配置已修改，是否保存？"),
        QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
    
    if (reply == QMessageBox::Cancel) {
        return false;
    }
    
    if (reply == QMessageBox::Yes) {
        onSaveConfig();
    }
    
    return true;
}

void MainWindow::closeEvent(QCloseEvent *event) {
    // 关闭窗口时最小化到托盘
    if (m_trayIcon && m_trayIcon->isVisible()) {
        hide();
        showTrayMessage(tr("Modbus PlexLink"), 
            tr("程序已最小化到系统托盘，继续在后台运行"));
        event->ignore();
        return;
    }
    
    if (!saveConfigIfNeeded()) {
        event->ignore();
        return;
    }
    
    // 停止所有通道
    m_channelManager->stopAll();
    
    event->accept();
}

void MainWindow::changeEvent(QEvent *event) {
    if (event->type() == QEvent::WindowStateChange) {
        // 最小化时隐藏到托盘
        if (isMinimized() && m_trayIcon && m_trayIcon->isVisible()) {
            QTimer::singleShot(0, this, &MainWindow::hide);
            showTrayMessage(tr("Modbus PlexLink"), 
                tr("程序已最小化到系统托盘"));
            event->ignore();
            return;
        }
    }
    QMainWindow::changeEvent(event);
}

bool MainWindow::eventFilter(QObject* watched, QEvent* event) {
    if (watched == m_alarmIndicator && event->type() == QEvent::MouseButtonRelease) {
        onShowAlarmManager();
        return true;
    }
    return QMainWindow::eventFilter(watched, event);
}

void MainWindow::createSystemTray() {
    // 创建托盘图标
    m_trayIcon = new QSystemTrayIcon(this);
    // 使用窗口图标作为托盘图标
    QIcon trayIcon = windowIcon();
    if (trayIcon.isNull()) {
        // 如果没有窗口图标，创建一个简单的默认图标
        QPixmap pixmap(32, 32);
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setBrush(QColor(34, 139, 34));
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(4, 4, 24, 24);
        painter.setPen(QPen(Qt::white, 2));
        painter.setFont(QFont("Arial", 12, QFont::Bold));
        painter.drawText(pixmap.rect(), Qt::AlignCenter, "M");
        trayIcon = QIcon(pixmap);
    }
    m_trayIcon->setIcon(trayIcon);
    m_trayIcon->setToolTip(tr("Modbus PlexLink - 数据采集与虚拟化服务系统"));
    
    // 创建托盘菜单
    m_trayMenu = new QMenu(this);
    
    m_showHideAction = new QAction(tr("显示主窗口"), this);
    connect(m_showHideAction, &QAction::triggered, this, &MainWindow::onShowHide);
    m_trayMenu->addAction(m_showHideAction);
    
    m_trayMenu->addSeparator();
    
    // 添加启动/停止所有通道选项
    m_trayMenu->addAction(m_startAllAction);
    m_trayMenu->addAction(m_stopAllAction);
    
    m_trayMenu->addSeparator();
    
    m_trayExitAction = new QAction(tr("退出程序"), this);
    connect(m_trayExitAction, &QAction::triggered, this, &MainWindow::onTrayExit);
    m_trayMenu->addAction(m_trayExitAction);
    
    m_trayIcon->setContextMenu(m_trayMenu);
    
    // 连接双击事件
    connect(m_trayIcon, &QSystemTrayIcon::activated,
            this, &MainWindow::onTrayIconActivated);
    
    // 显示托盘图标
    m_trayIcon->show();
}

void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) {
    if (reason == QSystemTrayIcon::DoubleClick) {
        onShowHide();
    }
}

void MainWindow::onShowHide() {
    if (isVisible() && !isMinimized()) {
        hide();
        m_showHideAction->setText(tr("显示主窗口"));
        showTrayMessage(tr("Modbus PlexLink"), 
            tr("程序已最小化到系统托盘"));
    } else {
        show();
        setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
        raise();
        activateWindow();
        m_showHideAction->setText(tr("隐藏主窗口"));
    }
}

void MainWindow::onTrayExit() {
    // 真正退出程序
    m_trayIcon->hide();
    
    if (!saveConfigIfNeeded()) {
        return;
    }
    
    // 停止所有通道
    m_channelManager->stopAll();
    
    QApplication::quit();
}

void MainWindow::showTrayMessage(const QString& title, const QString& message) {
    if (m_trayIcon && m_trayIcon->isVisible() && m_trayIcon->supportsMessages()) {
        m_trayIcon->showMessage(title, message, QSystemTrayIcon::Information, 3000);
    }
}

void MainWindow::autoStartAllChannels() {
    int count = m_channelManager->getChannelCount();
    if (count > 0) {
        qInfo() << "Auto-starting all channels on startup:" << count << "channels";
        m_channelManager->startAll();
        statusBar()->showMessage(
            tr("自动启动 %1 个通道...").arg(count), 5000);
        showTrayMessage(tr("Modbus PlexLink"), 
            tr("已自动启动 %1 个通道").arg(count));
    }
}

void MainWindow::applyModernTheme() {
    // 全局样式表 - 现代浅色主题
    QString modernStyle = R"(
        /* 主窗口背景 */
        QMainWindow {
            background-color: #F9FAFB;
        }

        /* 左侧面板 */
        #leftPanel {
            background-color: #F3F4F6;
            border-right: 1px solid #E5E7EB;
        }

        /* 右侧面板 */
        #dashboardPanel {
            background-color: white;
            border: 1px solid #E5E7EB;
            border-radius: 8px;
        }

        #panelTitle {
            color: #111827;
            padding: 4px 0px;
        }

        /* 分割器样式 */
        QSplitter::handle {
            background-color: #E5E7EB;
        }

        QSplitter::handle:horizontal {
            width: 1px;
        }

        QSplitter::handle:vertical {
            height: 1px;
        }

        QSplitter::handle:hover {
            background-color: #3B82F6;
        }

        /* 滚动条样式 */
        QScrollArea {
            border: none;
            background-color: transparent;
        }

        QScrollBar:vertical {
            border: none;
            background: #F3F4F6;
            width: 10px;
            margin: 0px;
        }

        QScrollBar::handle:vertical {
            background: #D1D5DB;
            min-height: 20px;
            border-radius: 5px;
        }

        QScrollBar::handle:vertical:hover {
            background: #9CA3AF;
        }

        QScrollBar::add-line:vertical,
        QScrollBar::sub-line:vertical {
            height: 0px;
        }

        /* 头部图标按钮 */
        #iconButtonHeader {
            background-color: #3B82F6;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14pt;
        }

        #iconButtonHeader:hover {
            background-color: #2563EB;
        }

        #iconButtonHeader:pressed {
            background-color: #1D4ED8;
        }

        /* 菜单栏样式 */
        QMenuBar {
            background-color: white;
            border-bottom: 1px solid #E5E7EB;
            padding: 4px;
        }

        QMenuBar::item {
            background-color: transparent;
            padding: 6px 12px;
            border-radius: 4px;
            color: #374151;
        }

        QMenuBar::item:selected {
            background-color: #F3F4F6;
        }

        QMenuBar::item:pressed {
            background-color: #E5E7EB;
        }

        /* 工具栏样式 */
        QToolBar {
            background-color: white;
            border-bottom: 1px solid #E5E7EB;
            spacing: 4px;
            padding: 4px;
        }

        QToolButton {
            background-color: transparent;
            border: 1px solid transparent;
            border-radius: 4px;
            padding: 6px;
            color: #374151;
        }

        QToolButton:hover {
            background-color: #F3F4F6;
            border-color: #E5E7EB;
        }

        QToolButton:pressed {
            background-color: #E5E7EB;
        }

        /* 状态栏样式 */
        QStatusBar {
            background-color: white;
            border-top: 1px solid #E5E7EB;
            color: #6B7280;
        }

        QStatusBar::item {
            border: none;
        }
    )";

    setStyleSheet(modernStyle);
}

// ============================================================================
// 通道卡片管理
// ============================================================================

void MainWindow::updateChannelCards() {
    // 清除现有卡片
    qDeleteAll(m_channelCards);
    m_channelCards.clear();

    // 清空布局
    QLayoutItem* item;
    while ((item = m_channelListLayout->takeAt(0)) != nullptr) {
        delete item->widget();
        delete item;
    }

    // 获取所有通道
    QList<Channel*> channels = m_channelManager->getAllChannels();

    if (channels.isEmpty()) {
        // 显示空状态
        QLabel* emptyLabel = new QLabel(tr("暂无通道\n\n点击 ➕ 创建新通道"), m_channelListWidget);
        emptyLabel->setAlignment(Qt::AlignCenter);
        emptyLabel->setStyleSheet(R"(
            QLabel {
                color: #9CA3AF;
                font-size: 12px;
                padding: 40px 20px;
            }
        )");
        m_channelListLayout->addWidget(emptyLabel);
    } else {
        // 创建通道卡片
        for (Channel* channel : channels) {
            ChannelCardWidget* card = new ChannelCardWidget(channel, m_channelListWidget);

            // 连接信号
            connect(card, &ChannelCardWidget::clicked,
                    this, &MainWindow::selectChannel);
            connect(card, &ChannelCardWidget::startRequested,
                    this, [this](Channel* ch) {
                        if (ch) {
                            ch->start();
                        }
                    });
            connect(card, &ChannelCardWidget::stopRequested,
                    this, [this](Channel* ch) {
                        if (ch) {
                            ch->stop();
                        }
                    });
            connect(card, &ChannelCardWidget::editRequested,
                    this, [this](Channel* ch) {
                        if (ch) {
                            m_currentChannel = ch;
                            onEditChannel();
                        }
                    });
            connect(card, &ChannelCardWidget::deleteRequested,
                    this, [this](Channel* ch) {
                        if (ch) {
                            m_currentChannel = ch;
                            onDeleteChannel();
                        }
                    });

            m_channelCards.append(card);
            m_channelListLayout->addWidget(card);
        }
    }

    // 添加弹簧
    m_channelListLayout->addStretch();

    // 如果有通道且没有选中，选中第一个
    if (!channels.isEmpty() && !m_currentChannel) {
        selectChannel(channels.first());
    }
}

void MainWindow::selectChannel(Channel* channel) {
    if (m_currentChannel == channel) {
        return;  // 已经选中
    }

    // 断开旧通道的信号连接
    if (m_currentChannel) {
        disconnect(m_currentChannel, nullptr, this, nullptr);
        if (m_messageLogPanel && m_messageLogPanel->getMessageViewer()) {
            disconnect(m_currentChannel, nullptr, m_messageLogPanel->getMessageViewer(), nullptr);
        }
    }

    // 更新选中状态
    for (ChannelCardWidget* card : m_channelCards) {
        card->setSelected(card->getChannel() == channel);
    }

    m_currentChannel = channel;

    // 更新右侧数据面板
    if (m_dashboardWidget) {
        m_dashboardWidget->setChannel(channel);
    }

    // 更新报文日志面板
    if (m_messageLogPanel) {
        m_messageLogPanel->setChannel(channel);

        // 连接新通道的Modbus报文信号
        if (channel && m_messageLogPanel->getMessageViewer()) {
            connect(channel, &Channel::modbusMessage,
                    this, [this](const QString& source, const QString& direction,
                                const QString& device, const QString& function,
                                const QString& address, const QString& data, bool success) {
                        if (m_messageLogPanel && m_messageLogPanel->getMessageViewer()) {
                            m_messageLogPanel->getMessageViewer()->addMessage(
                                direction, source + ":" + device, function, address, data, success);
                        }
                    });
        }
    }

    // 更新状态栏
    if (channel) {
        statusBar()->showMessage(tr("已选中通道: %1").arg(channel->getName()), 3000);
    }
}

Channel* MainWindow::getSelectedChannel() const {
    return m_currentChannel;
}

// ============================================================================
// 更新 onChannelCreated/Deleted/StateChanged 方法
// ============================================================================

void MainWindow::onChannelCreated(const QString& name) {
    qInfo() << "Channel created:" << name;
    updateChannelCards();  // 重新生成卡片
    updateStatusBar();
    updateActions();
    m_configModified = true;
}

void MainWindow::onChannelDeleted(const QString& name) {
    qInfo() << "Channel deleted:" << name;

    // 如果删除的是当前选中的通道
    if (m_currentChannel && m_currentChannel->getName() == name) {
        m_currentChannel = nullptr;
    }

    updateChannelCards();  // 重新生成卡片
    updateStatusBar();
    updateActions();
    m_configModified = true;
}

void MainWindow::onChannelStateChanged(const QString& name, ChannelState state) {
    // 找到对应的卡片并更新
    for (ChannelCardWidget* card : m_channelCards) {
        if (card->getChannel() && card->getChannel()->getName() == name) {
            card->updateDisplay();
            break;
        }
    }

    updateStatusBar();

    // 如果是当前选中的通道，更新数据面板
    if (m_currentChannel && m_currentChannel->getName() == name) {
        if (state == ChannelState::Running) {
            // 刷新数据显示
            if (m_dashboardWidget) {
                m_dashboardWidget->refreshDisplay();
            }
        }
    }
}

// ============================================================================
// 新的 updateChannelTable 实现（适配卡片列表）
// ============================================================================

void MainWindow::updateChannelTable() {
    // 更新所有卡片的显示
    for (ChannelCardWidget* card : m_channelCards) {
        card->updateDisplay();
    }
}

// ============================================================================
// 获取选中通道名称（兼容旧代码）
// ============================================================================

QString MainWindow::getSelectedChannelName() const {
    if (m_currentChannel) {
        return m_currentChannel->getName();
    }
    return QString();
}

} // namespace ModbusPlexLink
